<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/saiki.jpeg?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/saiki.jpeg?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="MongoDB,">










<meta name="description" content="(可参考:http://www.runoob.com/mongodb/mongodb-map-reduce.html) Map-Reduce是一种计算模型，简单的说就是将大批量的工作（数据）分解（MAP）执行，然后再将结果合并成最终结果（REDUCE）。 MongoDB提供的Map-Reduce非常灵活，对于大规模数据分析也相当实用。以下是MapReduce的基本语法：12345678910&amp;gt">
<meta name="keywords" content="MongoDB">
<meta property="og:type" content="article">
<meta property="og:title" content="MongoDB 聚合(二) MpaReduce">
<meta property="og:url" content="http://yoursite.com/2020/06/14/MongoDB 聚合(二) MapReduce/index.html">
<meta property="og:site_name" content="Penn">
<meta property="og:description" content="(可参考:http://www.runoob.com/mongodb/mongodb-map-reduce.html) Map-Reduce是一种计算模型，简单的说就是将大批量的工作（数据）分解（MAP）执行，然后再将结果合并成最终结果（REDUCE）。 MongoDB提供的Map-Reduce非常灵活，对于大规模数据分析也相当实用。以下是MapReduce的基本语法：12345678910&amp;gt">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-06-14T09:19:44.359Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MongoDB 聚合(二) MpaReduce">
<meta name="twitter:description" content="(可参考:http://www.runoob.com/mongodb/mongodb-map-reduce.html) Map-Reduce是一种计算模型，简单的说就是将大批量的工作（数据）分解（MAP）执行，然后再将结果合并成最终结果（REDUCE）。 MongoDB提供的Map-Reduce非常灵活，对于大规模数据分析也相当实用。以下是MapReduce的基本语法：12345678910&amp;gt">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2020/06/14/MongoDB 聚合(二) MapReduce/">





  <title>MongoDB 聚合(二) MpaReduce | Penn</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Penn</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">my blog</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-schedule">
          <a href="/schedule/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br>
            
            日程表
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br>
            
            站点地图
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/06/14/MongoDB 聚合(二) MapReduce/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Shen">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/saiki.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Penn">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">MongoDB 聚合(二) MpaReduce</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-06-14T17:19:44+08:00">
                2020-06-14
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/技术/" itemprop="url" rel="index">
                    <span itemprop="name">技术</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2020/06/14/MongoDB 聚合(二) MapReduce/" class="leancloud_visitors" data-flag-title="MongoDB 聚合(二) MpaReduce">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>(可参考:<a href="http://www.runoob.com/mongodb/mongodb-map-reduce.html" target="_blank" rel="noopener">http://www.runoob.com/mongodb/mongodb-map-reduce.html</a>)</p>
<p>Map-Reduce是一种计算模型，简单的说就是将大批量的工作（数据）分解（MAP）执行，然后再将结果合并成最终结果（REDUCE）。</p>
<p>MongoDB提供的Map-Reduce非常灵活，对于大规模数据分析也相当实用。<br>以下是MapReduce的基本语法：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.collection.mapReduce(</span><br><span class="line">   function() &#123;emit(key,value);&#125;,  //map 函数</span><br><span class="line">   function(key,values) &#123;return reduceFunction&#125;,   //reduce 函数</span><br><span class="line">   &#123;</span><br><span class="line">      out: collection,</span><br><span class="line">      query: document,</span><br><span class="line">      sort: document,</span><br><span class="line">      limit: number</span><br><span class="line">   &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure></p>
<p>使用 MapReduce 要实现两个函数 Map 函数和 Reduce 函数,Map 函数调用 emit(key, value), 遍历 collection 中所有的记录, 将 key 与 value 传递给 Reduce 函数进行处理。</p>
<p>Map 函数必须调用 emit(key, value) 返回键值对。<br>参数说明:</p>
<ul>
<li><code>map</code> ：映射函数 (生成键值对序列,作为 reduce 函数参数)。</li>
<li><code>reduce</code> 统计函数，reduce函数的任务就是将key-values变成key-value，也就是把values数组变成一个单一的值value。。</li>
<li><code>out</code> 统计结果存放集合 (不指定则使用临时集合,在客户端断开后自动删除)。</li>
<li><code>query</code> 一个筛选条件，只有满足条件的文档才会调用map函数。（query。limit，sort可以随意组合）</li>
<li><code>sort</code> 和limit结合的sort排序参数（也是在发往map函数前给文档排序），可以优化分组机制</li>
<li><code>limit</code> 发往map函数的文档数量的上限（要是没有limit，单独使用sort的用处不大）</li>
</ul>
<p>以下实例在集合 orders 中查找 status:”A” 的数据，并根据 cust_id 来分组，并计算 amount 的总和。</p>
<p><a href="http://www.runoob.com/mongodb/mongodb-map-reduce.html" target="_blank" rel="noopener">http://www.runoob.com/mongodb/mongodb-map-reduce.html</a></p>
<p>考虑以下文档结构存储用户的文章，文档存储了用户的 user_name 和文章的 status 字段：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.posts.insert(&#123;</span><br><span class="line">   &quot;post_text&quot;: &quot;菜鸟教程，最全的技术文档。&quot;,</span><br><span class="line">   &quot;user_name&quot;: &quot;mark&quot;,</span><br><span class="line">   &quot;status&quot;:&quot;active&quot;</span><br><span class="line">&#125;)</span><br><span class="line">WriteResult(&#123; &quot;nInserted&quot; : 1 &#125;)</span><br><span class="line">&gt;db.posts.insert(&#123;</span><br><span class="line">   &quot;post_text&quot;: &quot;菜鸟教程，最全的技术文档。&quot;,</span><br><span class="line">   &quot;user_name&quot;: &quot;mark&quot;,</span><br><span class="line">   &quot;status&quot;:&quot;active&quot;</span><br><span class="line">&#125;)</span><br><span class="line">WriteResult(&#123; &quot;nInserted&quot; : 1 &#125;)</span><br><span class="line">&gt;db.posts.insert(&#123;</span><br><span class="line">   &quot;post_text&quot;: &quot;菜鸟教程，最全的技术文档。&quot;,</span><br><span class="line">   &quot;user_name&quot;: &quot;mark&quot;,</span><br><span class="line">   &quot;status&quot;:&quot;active&quot;</span><br><span class="line">&#125;)</span><br><span class="line">WriteResult(&#123; &quot;nInserted&quot; : 1 &#125;)</span><br><span class="line">&gt;db.posts.insert(&#123;</span><br><span class="line">   &quot;post_text&quot;: &quot;菜鸟教程，最全的技术文档。&quot;,</span><br><span class="line">   &quot;user_name&quot;: &quot;mark&quot;,</span><br><span class="line">   &quot;status&quot;:&quot;active&quot;</span><br><span class="line">&#125;)</span><br><span class="line">WriteResult(&#123; &quot;nInserted&quot; : 1 &#125;)</span><br><span class="line">&gt;db.posts.insert(&#123;</span><br><span class="line">   &quot;post_text&quot;: &quot;菜鸟教程，最全的技术文档。&quot;,</span><br><span class="line">   &quot;user_name&quot;: &quot;mark&quot;,</span><br><span class="line">   &quot;status&quot;:&quot;disabled&quot;</span><br><span class="line">&#125;)</span><br><span class="line">WriteResult(&#123; &quot;nInserted&quot; : 1 &#125;)</span><br><span class="line">&gt;db.posts.insert(&#123;</span><br><span class="line">   &quot;post_text&quot;: &quot;菜鸟教程，最全的技术文档。&quot;,</span><br><span class="line">   &quot;user_name&quot;: &quot;runoob&quot;,</span><br><span class="line">   &quot;status&quot;:&quot;disabled&quot;</span><br><span class="line">&#125;)</span><br><span class="line">WriteResult(&#123; &quot;nInserted&quot; : 1 &#125;)</span><br><span class="line">&gt;db.posts.insert(&#123;</span><br><span class="line">   &quot;post_text&quot;: &quot;菜鸟教程，最全的技术文档。&quot;,</span><br><span class="line">   &quot;user_name&quot;: &quot;runoob&quot;,</span><br><span class="line">   &quot;status&quot;:&quot;disabled&quot;</span><br><span class="line">&#125;)</span><br><span class="line">WriteResult(&#123; &quot;nInserted&quot; : 1 &#125;)</span><br><span class="line">&gt;db.posts.insert(&#123;</span><br><span class="line">   &quot;post_text&quot;: &quot;菜鸟教程，最全的技术文档。&quot;,</span><br><span class="line">   &quot;user_name&quot;: &quot;runoob&quot;,</span><br><span class="line">   &quot;status&quot;:&quot;active&quot;</span><br><span class="line">&#125;)</span><br><span class="line">WriteResult(&#123; &quot;nInserted&quot; : 1 &#125;)</span><br></pre></td></tr></table></figure></p>
<p>现在，我们将在 posts 集合中使用 mapReduce 函数来选取已发布的文章(status:”active”)，并通过user_name分组，计算每个用户的文章数：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.posts.mapReduce( </span><br><span class="line">   function() &#123; emit(this.user_name,1); &#125;, </span><br><span class="line">   function(key, values) &#123;return Array.sum(values)&#125;, </span><br><span class="line">      &#123;  </span><br><span class="line">         query:&#123;status:&quot;active&quot;&#125;,  </span><br><span class="line">         out:&quot;post_total&quot; </span><br><span class="line">      &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure></p>
<p>以上 mapReduce 输出结果为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">        &quot;result&quot; : &quot;post_total&quot;,</span><br><span class="line">        &quot;timeMillis&quot; : 23,</span><br><span class="line">        &quot;counts&quot; : &#123;</span><br><span class="line">                &quot;input&quot; : 5,</span><br><span class="line">                &quot;emit&quot; : 5,</span><br><span class="line">                &quot;reduce&quot; : 1,</span><br><span class="line">                &quot;output&quot; : 2</span><br><span class="line">        &#125;,</span><br><span class="line">        &quot;ok&quot; : 1</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>结果表明，共有 5 个符合查询条件（status:”active”）的文档， 在map函数中生成了 5 个键值对文档，最后使用reduce函数将相同的键值分为 2 组。</p>
<p>具体参数说明：</p>
<ul>
<li><code>result</code>：储存结果的collection的名字,这是个临时集合，MapReduce的连接关闭后自动就被删除了。</li>
<li><code>timeMillis</code>：执行花费的时间，毫秒为单位</li>
<li><code>input</code>：满足条件被发送到map函数的文档个数</li>
<li><code>emit</code>：在map函数中emit被调用的次数，也就是所有集合中的数据总量</li>
<li><code>ouput</code>：结果集合中的文档个数（count对调试非常有帮助）</li>
<li><code>ok</code>：是否成功，成功为1</li>
<li><code>err</code>：如果失败，这里可以有失败原因，不过从经验上来看，原因比较模糊，作用不大</li>
</ul>
<p>使用 find 操作符来查看 mapReduce 的查询结果：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.posts.mapReduce( </span><br><span class="line">   function() &#123; emit(this.user_name,1); &#125;, </span><br><span class="line">   function(key, values) &#123;return Array.sum(values)&#125;, </span><br><span class="line">      &#123;  </span><br><span class="line">         query:&#123;status:&quot;active&quot;&#125;,  </span><br><span class="line">         out:&quot;post_total&quot; </span><br><span class="line">      &#125;</span><br><span class="line">).find()</span><br></pre></td></tr></table></figure></p>
<p>以上查询显示如下结果:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#123; &quot;_id&quot; : &quot;mark&quot;, &quot;value&quot; : 4 &#125;</span><br><span class="line">&#123; &quot;_id&quot; : &quot;runoob&quot;, &quot;value&quot; : 1 &#125;</span><br></pre></td></tr></table></figure></p>
<p>用类似的方式，MapReduce可以被用来构建大型复杂的聚合查询。</p>
<p>Map函数和Reduce函数可以使用 JavaScript 来实现，使得MapReduce的使用非常灵活和强大。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>这两个图片是什么?可以扫吗?</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatPay.png" alt="Shen 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/aliPay.png" alt="Shen 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/MongoDB/" rel="tag"># MongoDB</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/06/14/MongoDB 聚合(三) aggregate()/" rel="next" title="MongoDB 聚合(三) aggregate()">
                <i class="fa fa-chevron-left"></i> MongoDB 聚合(三) aggregate()
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MjA1OS8xODYwNg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/saiki.jpeg" alt="Shen">
            
              <p class="site-author-name" itemprop="name">Shen</p>
              <p class="site-description motion-element" itemprop="description">Penn's blog</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">117</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">26</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Shen</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("Gst71Gv0w5HKejm5H7LuG0XI-gzGzoHsz", "aoFAyHFDKihGTWWhHX0p8byC");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
